/** 
 * @Description: 文件描述
 * @Author: 程前
 * @Date: 2024-12-02 15:28:24
 * @LastEditors: 程前
 * @LastEditTime: 2025-01-20 15:03:41
 */

import { useCesiumGlobalStore } from "@/store/modules/cesiun-global"
import { ElLoading } from 'element-plus'
import type { LoadingOptions } from "element-plus"
import { LoadingInstance } from 'element-plus/lib/components/loading/src/loading'

/**
 * 获取assets静态资源
 * @param url 
 * @returns 
 */
export const getAssetsFile = (url: string) => {
    return new URL(`/src/assets/${url}`, import.meta.url).href
}

/**
 * 节流函数
 * @param fn 需要节流的函数
 * @param delay 延迟时间（毫秒）
 */
export const throttle = (fn: Function, delay: number) => {
    let lastTime = 0;
    return function (...args: any[]) {
        const now = Date.now();
        if (now - lastTime >= delay) {
            fn.apply(this, args);
            lastTime = now;
        }
    };
}



/**
 * 销毁当前loader
 */
export const clearLoader = () => {
    const cesiumGlobalStore = useCesiumGlobalStore()
    const loader = cesiumGlobalStore.getLoader()
    if (loader) {
        loader.destroy()
    }
}

/**
 * 设置全局loading
 * @param options  
 * @returns loading实例
 */
export const setLoading = (options: LoadingOptions): LoadingInstance => {
    return ElLoading.service({
        fullscreen: true,
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
        ...options
    });
}

/**
 * 读取svg文件信息
 * @param url 
 * @returns 
 */
export const getSvgData = async (url: string) => {
    const data = await fetch(url)
    const res = await data.text()
    return res
}

/**
 * 将16进制颜色转换为rgba格式
 * @param hex 16进制颜色值 支持#fff、#ffffff格式
 * @param opacity 自定义透明度 0-1
 * @returns rgba格式颜色值
 */
export const hexToRGBA = (hex: string, opacity: number = 1): string => {
    // 移除#号
    hex = hex.replace('#', '');

    // 将3位色值转换为6位
    if (hex.length === 3) {
        hex = hex.split('').map(char => char + char).join('');
    }

    // 解析RGB值
    const r = parseInt(hex.slice(0, 2), 16);
    const g = parseInt(hex.slice(2, 4), 16);
    const b = parseInt(hex.slice(4, 6), 16);

    // 确保透明度在0-1范围内
    opacity = Math.max(0, Math.min(1, opacity));

    // 返回rgba格式
    return `rgba(${r}, ${g}, ${b}, ${opacity})`;
}


/**
 * @description 将urlTemplate里面{xx}对应的xx值，不传不做改变
 * @param {String} urlTemplate 地址字符串：如'//webst{s}.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}'
 * @param {Object | any} params 要修改的参数
 * @return {String}
 */
export const replacePlaceholders = (urlTemplate: string | any, params: Object | any): string => {
    return urlTemplate.replace(/{(\w+)}/g, (_: any, key: string) => {
        return key in params ? params[key] : `{${key}}`
    })
}
